﻿using System;
using System.Collections.Specialized;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using IntraVision.Web;
using IntraVision.Web.Security;
using Model;
using NotarialFormMdbExport;
using System.Data;
using ADOXJetXML;
using System.Configuration;
using System.IO;
using LZMA;
using System.Data.Linq;
using System.Text;

public class EnotExportController : EntityListController<EnotExportHistory, NotarialServiceDataContext>
{
    private string ChamberID = ConfigurationManager.AppSettings["EnotChamberID"];
    private string NotaryID = ConfigurationManager.AppSettings["EnotNotaryID"];
    private string EnotTempDirectory = ConfigurationManager.AppSettings["EnotTempDirectory"];

    public void Default()
    {
        TemplatePath = "~/views/enotexport/form.haml";
        LayoutPath = "~/views/layouts/page.haml";
        RegisterFormScripts();
        
        using (var dc = new NotarialServiceDataContext())
        {
            var lastExportDate = GetLastExportDate(dc);
            ViewData["date"] = lastExportDate.HasValue ? lastExportDate.ToString() : string.Empty;
            RenderView();
        }
    }

    public override void View(string entityid)
    {
        using (var dc = new NotarialServiceDataContext())
        {
            var entity = dc.EnotExportHistory.FirstOrDefault(e => e.Id == Convert.ToInt32(entityid));
            var fileName = string.Format("enot_export_data_{0}.mdb", entity.ExportDate.ToFileTimeUtc());

            Response.ContentType = "application/octet-stream";
            Response.AppendHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
            Response.HeaderEncoding = Encoding.GetEncoding("windows-1251");
            Response.ContentEncoding = Encoding.GetEncoding("windows-1251");

            byte[] bytes;
            try
            {
                bytes = Extractor.ExtractBytes(entity.Data.ToArray());
            }
            catch
            {
                bytes = entity.Data.ToArray();
            }
            Response.BinaryWrite(bytes);

            Response.Flush();
            Response.End();
        }
    }

    public void Export()
    {
        using (var dc = new NotarialServiceDataContext())
        {
            var currentDate = DateTime.Now;
            var startDate = GetLastExportDate(dc);
            var dateRange = new DateRange { StartDate = startDate ?? DateTime.Now.AddYears(-20), EndDate = currentDate };

            var ds = GetExportDataSet(dc, dateRange);            

            var fileName = string.Format("enot_export_data_{0}.mdb", currentDate.ToFileTimeUtc());
            var filePath = Path.Combine(EnotTempDirectory, fileName); 
            DatasetToJetConverter.CopyDatasetToJetDB(ds, filePath);

            var data = File.ReadAllBytes(filePath);

            SaveHistory(dc, currentDate, data);
            
            dc.SubmitChanges();

            Response.ContentType = "application/octet-stream";
            Response.AppendHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
            Response.HeaderEncoding = Encoding.GetEncoding("windows-1251");
            Response.ContentEncoding = Encoding.GetEncoding("windows-1251");

            Response.BinaryWrite(data);

            Response.Flush();
            Response.End();
        }
    }

    private static void SaveHistory(NotarialServiceDataContext dc, DateTime currentDate, byte[] data)
    {
        var history = new EnotExportHistory { ExportDate = currentDate };

        try
        {
            history.Data = new System.Data.Linq.Binary(Compressor.CompressBytes(data));
        }
        catch
        {
            history.Data = new System.Data.Linq.Binary(data);
        }

        dc.EnotExportHistory.InsertOnSubmit(history);
    }

    private DateTime? GetLastExportDate(NotarialServiceDataContext dc)
    {
        if (!dc.EnotExportHistory.Any())
            return null;
        return dc.EnotExportHistory.Max(t => t.ExportDate);
    }

    private DataSet GetExportDataSet(NotarialServiceDataContext dc, DateRange dateRange)
    {
        var tf = new ExportTableFactory(
                    new Model.NotarialFormEnot.Configuration
                    {
                        ChamberID = this.ChamberID,
                        NotaryID = this.NotaryID,
                        DocTypes = new Dictionary<int, string>()
                    });

        var ds = new DataSet();
        var dt = tf.GetTable(dc, dateRange);
        ds.Tables.Add(dt);
        ds.AcceptChanges();

        return ds;
    }
}
